
class UIToggleItem < UIMenuItem
  attr_reader :value

  def initialize(window, delegate, text, default_val = false)
    super(window, delegate, text)
    @value = default_val # switched off by default
    @text = text
    @t_color = Gosu::Color.new(0xffffffff)
    @hover_color = 0xffddddff
    @button_image = window.load_tiles('../3d_renders/toggle_item.png', 150, 50)
    @text_border = 0
    @image_index = (@value) ? @button_image.size - 1 : 0
  end

  def update(x, y, width, height, mouse_x, mouse_y)
    # calculate dimensions of background image before drawing.
    # also determine whether the mouse is hovering over valid content.
    super # sets @x, @y, @width, @height, and @color
    # do simple animation here
    @image_index += 1 if @value
    @image_index -= 1 if @image_index >= @button_image.size
    @image_index -= 1 if !@value
    @image_index += 1 if @image_index < 0
    border_x = width.to_f / 6
    border_y = height.to_f / 3
    @image_x, @image_y = @x + border_x, @y + border_y
    @image_w, @image_h = @width - 2*border_x, @height - border_y
    @text_pos = @y + height/4 # above the box
    return if @state == :disabled

    #ensure the button color stays normal unless mouse_over gets called.
    if mouse_x >= @image_x and mouse_x <= @image_x + @image_w and
      mouse_y >= @image_y and mouse_y <= @image_y + @image_h
        mouse_over
    else
      @state = :static
    end
  end

  def draw
    @button_image[@image_index].draw_as_quad(@image_x, @image_y, @color,
                        @image_x + @image_w, @image_y, @color,
                        @image_x + @image_w, @image_y + @image_h, @color,
                        @image_x, @image_y + @image_h, @color,
                        ZOrder::BUTTON)
    @font.draw_rel(@text, @image_x + @image_w/2, @text_pos,
                   ZOrder::TEXT, 0.5, 0.5, 1, 1, @t_color)
  end

  def clicked(left_or_right, mx, my)
    return if @state != :hover
    case left_or_right
    when :left
      @selected_sound.play
      @value = !@value
    when :right
      # Do nothing. But maybe add something later.
    end
  end

  def set_value(value)
    @value = value # true or false
  end

end
